//
//  TopCollectionLayout.m
//  网易头部滚动条
//
//  Created by dllo on 16/8/3.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "TopCollectionLayout.h"

@interface TopCollectionLayout ()

@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArray;
@property (nonatomic, assign) CGFloat frontAllItemWidth;

@end

@implementation TopCollectionLayout

//- (instancetype)init
//{
//    self = [super init];
//    if (self) {
//        [self prepareLayout];
//    }
//    return self;
//}

- (void)prepareLayout
{
    [super prepareLayout];
    if (_attributesArray.count != 0) {
        [_attributesArray removeAllObjects];
    }
    if (_sectionInset.top + _sectionInset.bottom + _itemSize.height > self.collectionView.frame.size.height) {
        NSLog(@"Error: item越界, 请修改item的高度!");
        return;
    }
    _attributesArray = [NSMutableArray array];
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        [self createAttributesArray:i];
    }
}

- (void)createAttributesArray:(int)index
{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    if ([_delegate respondsToSelector:@selector(collectionView:topLayout:sizeForItemAtIndexPath:)]) {
        _itemSize = [_delegate collectionView:self.collectionView topLayout:self sizeForItemAtIndexPath:indexPath];
    }
    UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attribute.frame = CGRectMake(_sectionInset.left + index * _minimumIteritemSpacing + self.frontAllItemWidth, _sectionInset.top, _itemSize.width, _itemSize.height);
    [_attributesArray addObject:attribute];
    
    
    
}

- (CGFloat)frontAllItemWidth
{
    _frontAllItemWidth = 0;
    for (UICollectionViewLayoutAttributes *attribute in _attributesArray) {
        _frontAllItemWidth += CGRectGetWidth(attribute.frame);
    }
    return _frontAllItemWidth;
}

- (CGSize)collectionViewContentSize
{
    [super collectionViewContentSize];
    return CGSizeMake(self.frontAllItemWidth + _sectionInset.left + _sectionInset.right + ([self.collectionView numberOfItemsInSection:0] - 1) * _minimumIteritemSpacing, _itemSize.height + _sectionInset.top + _sectionInset.bottom);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    [super layoutAttributesForElementsInRect:rect];
    return _attributesArray;
}



@end
